package com.sjh.baseutils

import android.content.Context
import android.content.res.Resources
import android.os.Build
import android.util.TypedValue
import android.view.*
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.annotation.ColorRes
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.PermissionUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

/**
 * 一些不成套的扩展方法
 */

    /**
     * 快速保存sp
     */
    fun <T : Any> preference(
        name: String,
        defaultValue: T,
        defaultFileName: String,
        context: Context
    ) = Preference(
        context,
        name,
        defaultValue,
        defaultFileName
    )

    /**
     * 返回颜色
     */
    fun Context.color(@ColorRes id:Int):Int {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            return resources.getColor(id,null)
        }
        return resources.getColor(id)
    }

    fun androidx.fragment.app.Fragment.color(@ColorRes id:Int):Int {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            return resources.getColor(id,null)
        }
        return resources.getColor(id)
    }

    /**
     * 获取RadioGroup中，选中状态的button是第几个
     * 如果没有则返回-1
     */
    fun RadioGroup.getCheckOrder():Int=(0 until childCount).firstOrNull { (getChildAt(it) as RadioButton).isChecked }?: -1

    /**
     * 默认的获取FragmentStatePagerAdapter
     */
    fun getBaseFragmentStatePagerAdapter(fm: androidx.fragment.app.FragmentManager, list:List<androidx.fragment.app.Fragment>,behavior:Int = FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT): androidx.fragment.app.FragmentPagerAdapter {
        return object: androidx.fragment.app.FragmentPagerAdapter(fm,behavior) {
            override fun getItem(position: Int): androidx.fragment.app.Fragment {
                return list[position]
            }
            override fun getCount(): Int {
                return list.size
            }
            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            }
        }
    }

    /**
     * 给Viewpager设置适配器，并设置离屏加载数为list.size
     */
    fun androidx.viewpager.widget.ViewPager.setBaseAdapter(fm: androidx.fragment.app.FragmentManager, list:List<androidx.fragment.app.Fragment>,behavior:Int = FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT){
        adapter = getBaseFragmentStatePagerAdapter(
            fm,
            list,
            behavior
        )
        offscreenPageLimit = list.size
    }


//
//    /**
//     * 通过LayoutId便捷获取ViewDataBinding的方法
//     * 主要还是为了在 Activity 里面写R.layout.xxxxxx,方便点击跳转
//     */
//    fun <T : ViewDataBinding> AppCompatActivity.getDataBinding(@LayoutRes id:Int,parent:ViewGroup?=null,attachToParent:Boolean=parent!=null):T{
//        val binding = DataBindingUtil.inflate<T>(layoutInflater,id,parent,attachToParent)
//        binding.lifecycleOwner = this
//        return binding
//    }


    /**
     * 生成argb的颜色
     */
    fun argb(alpha: Float, red: Float, green: Float, blue: Float): Int {
        return (alpha * 255.0f + 0.5f).toInt() shl 24 or
                ((red * 255.0f + 0.5f).toInt() shl 16) or
                ((green * 255.0f + 0.5f).toInt() shl 8) or
                (blue * 255.0f + 0.5f).toInt()
    }

    /**
     * 简化Gson转化
     */
    inline fun <reified T> Gson.fromJson(s:String): T? {
        return fromJson<T>(s,object: TypeToken<T>(){}.type)
    }
    /**
     * 快速点击
     * 默认的所有click都是慢速点击的，如果需要快速点击，请调用这个方法
     */
    fun android.view.View.onFastClick(
            handler: (v: android.view.View?) -> Unit
    ) {
        //这里不能使用lambda表达式，因为需要给onClick添加@FastClick注解
        setOnClickListener(object : android.view.View.OnClickListener{
//            @FastClick
            override fun onClick(v: View?) {
                handler(v)
            }
        })
    }


/**
 * rxjava 绑定Android的生命周期
 */
fun <T> io.reactivex.Observable<T>.bindingLifecycle(lo : LifecycleOwner) = `as` (com.uber.autodispose.AutoDispose.autoDisposable(com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider.from(lo,Lifecycle.Event.ON_DESTROY)))
fun <T> io.reactivex.Observable<T>.bindingLifecycle(lo : Lifecycle) = `as` (com.uber.autodispose.AutoDispose.autoDisposable(com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider.from(lo,Lifecycle.Event.ON_DESTROY)))

/**
 * 检查权限
 * @param per 需要检查的权限
 * @param granted 同意权限后的操作
 * @param isForever 是否是永久拒绝
 */
fun checkPermission(@PermissionConstants.Permission per: Array<String>,onDenied:((isForever:Boolean)->Unit)?=null, granted:()->Unit){
    PermissionUtils.permission(*per)
            .rationale { activity, shouldRequest ->
                //永久拒绝权限
                onDenied?.invoke(true)
            }
            .callback(object : PermissionUtils.FullCallback {
                override fun onGranted(permissionsGranted: MutableList<String>?) {
                    //同意权限
                    granted.invoke()
                }
                override fun onDenied(permissionsDeniedForever: MutableList<String>?, permissionsDenied: MutableList<String>?) {
                    //拒绝权限
                    onDenied?.invoke(false)
                }
            }).request()
}
/**
 * 给所有数值类型增加一个属性，方便获取到该数值直接转dp的结果
 */
val Number.dp
    get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,this.toFloat(), Resources.getSystem().displayMetrics)
